import { onMounted, ref, watch, isRef } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'

/**
 * @name: useTable
 * @description: 获取列表数据
 * @params {url: String, params: Object, formatParams: Function, formatResult: Function, onSuccess: Function, immediate: Boolean, pagination: Boolean }
 * @return: {loading: Boolean, tableData: Array, pagination: Object, getData: Function }
 *
 */
export default function (props) {
  const { url, params = {}, formatParams, formatResult, onSuccess, immediate = false, pageLoading = false, pagination: isPage = true } = props
  const loading = ref(false)
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: +getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10,
    onChange: (pageNum, pageSize) => {
      pagination.value.current = pageNum
      pagination.value.pageSize = pageSize
    }
  })
  const tableData = ref([])
  const requestParams = ref({})
  const requestPage = ref({})

  const getData = async () => {
    loading.value = true
    const paramsData = isRef(params) ? params.value : params
    const { dateRange, ...rest } = paramsData
    const paramsFormat = {
      dateRange,
      ...rest,
      ...(dateRange && { stdate: dateRange[0], eddate: dateRange[1] })
    }
    isParamsChange.value && (pagination.value.current = 1)
    isParamsChange.value = false
    requestParams.value = formatParams ? formatParams(paramsFormat) : paramsFormat
    requestPage.value = isPage ? { pageNum: pagination.value.current, pageSize: pagination.value.pageSize } : {}
    const { code, data, msg, total } = await post(
      url,
      {
        ...requestParams.value,
        ...requestPage.value
      },
      { loading: pageLoading }
    )
    loading.value = false
    if (code !== 0) return message.error(msg || '请求失败')
    tableData.value = formatResult ? formatResult(data) : data
    pagination.value.total = total
    onSuccess && onSuccess(data)
  }
  //查询参数是否改变
  const isParamsChange = ref(false)
  watch(
    () => props.params,
    () => {
      isParamsChange.value = true
    },
    {
      deep: true
    }
  )
  watch(
    () => props.formatParams,
    () => {
      isParamsChange.value = true
    },
    {
      deep: true
    }
  )
  watch(
    () => pagination.value.current,
    () => getData()
  )
  watch(
    () => pagination.value.pageSize,
    () => {
      pagination.value.current = 1
      getData()
    }
  )
  onMounted(() => immediate && getData())
  return { loading, tableData, pagination, getData }
}
